/**
 * 键盘快捷键系统
 * 提供灵活的快捷键绑定和管理
 */

import { ref, onMounted, onUnmounted, computed } from 'vue'
import { ElMessage } from 'element-plus'

// 全局快捷键注册表
const globalShortcuts = new Map()
const shortcutHistory = []

export function useKeyboardShortcuts(shortcuts = {}, options = {}) {
  const {
    enabled = true,
    preventDefault = true,
    stopPropagation = false,
    scope = 'local', // local | global
    showHints = true
  } = options

  const isEnabled = ref(enabled)
  const activeShortcuts = ref(new Map())
  const pressedKeys = ref(new Set())
  const lastKeyCombo = ref('')

  // 快捷键配置
  const defaultShortcuts = {
    // 通用操作
    'ctrl+s': { action: 'save', label: '保存', icon: 'DocumentChecked' },
    'ctrl+z': { action: 'undo', label: '撤销', icon: 'RefreshLeft' },
    'ctrl+shift+z': { action: 'redo', label: '重做', icon: 'RefreshRight' },
    'ctrl+c': { action: 'copy', label: '复制', icon: 'DocumentCopy' },
    'ctrl+v': { action: 'paste', label: '粘贴', icon: 'Document' },
    'ctrl+x': { action: 'cut', label: '剪切', icon: 'Scissors' },
    'ctrl+a': { action: 'selectAll', label: '全选', icon: 'Select' },
    'ctrl+f': { action: 'find', label: '查找', icon: 'Search' },
    'delete': { action: 'delete', label: '删除', icon: 'Delete' },
    'escape': { action: 'cancel', label: '取消', icon: 'Close' },
    'enter': { action: 'confirm', label: '确认', icon: 'Check' },

    // 低代码平台专用
    'ctrl+k': { action: 'quickPanel', label: '快捷面板', icon: 'MagicStick' },
    'ctrl+p': { action: 'pageDesigner', label: '页面设计器', icon: 'Document' },
    'ctrl+shift+f': { action: 'formDesigner', label: '表单设计器', icon: 'Edit' },
    'ctrl+shift+a': { action: 'apiDesigner', label: 'API设计器', icon: 'Connection' },
    'ctrl+g': { action: 'codeGenerator', label: '代码生成器', icon: 'Cpu' },
    'ctrl+space': { action: 'aiAssistant', label: 'AI助手', icon: 'MagicStick' },
    'ctrl+h': { action: 'history', label: '历史记录', icon: 'Clock' },
    'ctrl+shift+s': { action: 'saveAs', label: '另存为', icon: 'FolderOpened' },
    'ctrl+shift+p': { action: 'preview', label: '预览', icon: 'View' },
    'ctrl+shift+d': { action: 'duplicate', label: '复制', icon: 'DocumentCopy' },

    // 视图控制
    'ctrl+=': { action: 'zoomIn', label: '放大', icon: 'ZoomIn' },
    'ctrl+-': { action: 'zoomOut', label: '缩小', icon: 'ZoomOut' },
    'ctrl+0': { action: 'resetZoom', label: '重置缩放', icon: 'FullScreen' },
    'ctrl+shift+h': { action: 'toggleHints', label: '显示/隐藏提示', icon: 'QuestionFilled' }
  }

  // 合并快捷键配置
  const mergedShortcuts = { ...defaultShortcuts, ...shortcuts }

  // 解析按键组合
  const parseKeyCombo = (combo) => {
    const parts = combo.toLowerCase().split('+').map(k => k.trim())
    return {
      ctrl: parts.includes('ctrl') || parts.includes('control'),
      shift: parts.includes('shift'),
      alt: parts.includes('alt'),
      meta: parts.includes('meta') || parts.includes('cmd'),
      key: parts[parts.length - 1]
    }
  }

  // 检查按键匹配
  const matchKeyCombo = (event, combo) => {
    const parsed = parseKeyCombo(combo)
    const key = event.key.toLowerCase()

    // 特殊键映射
    const keyMap = {
      'esc': 'escape',
      'del': 'delete',
      ' ': 'space'
    }

    const normalizedKey = keyMap[key] || key

    return (
      event.ctrlKey === parsed.ctrl &&
      event.shiftKey === parsed.shift &&
      event.altKey === parsed.alt &&
      event.metaKey === parsed.meta &&
      normalizedKey === parsed.key
    )
  }

  // 获取当前按键组合
  const getCurrentCombo = (event) => {
    const parts = []
    if (event.ctrlKey) parts.push('ctrl')
    if (event.shiftKey) parts.push('shift')
    if (event.altKey) parts.push('alt')
    if (event.metaKey) parts.push('meta')
    
    const key = event.key.toLowerCase()
    parts.push(key === ' ' ? 'space' : key)
    
    return parts.join('+')
  }

  // 处理按键事件
  const handleKeyDown = (event) => {
    if (!isEnabled.value) return

    // 记录按下的键
    pressedKeys.value.add(event.key.toLowerCase())

    // 获取当前组合
    const combo = getCurrentCombo(event)
    lastKeyCombo.value = combo

    // 查找匹配的快捷键
    for (const [shortcut, config] of Object.entries(mergedShortcuts)) {
      if (matchKeyCombo(event, shortcut)) {
        if (preventDefault) {
          event.preventDefault()
        }
        if (stopPropagation) {
          event.stopPropagation()
        }

        // 执行回调
        if (typeof config === 'function') {
          config(event)
        } else if (config.handler) {
          config.handler(event)
        }

        // 触发动作事件
        const action = typeof config === 'object' ? config.action : shortcut
        triggerAction(action, event)

        // 记录到历史
        recordShortcutUsage(shortcut, action)

        // 显示提示
        if (showHints && config.label) {
          showShortcutHint(config.label, shortcut)
        }

        break
      }
    }
  }

  // 处理按键释放
  const handleKeyUp = (event) => {
    pressedKeys.value.delete(event.key.toLowerCase())
  }

  // 触发动作
  const triggerAction = (action, event) => {
    // 可以在这里添加全局动作处理逻辑
    console.log('Shortcut action triggered:', action)
  }

  // 记录快捷键使用
  const recordShortcutUsage = (shortcut, action) => {
    shortcutHistory.push({
      shortcut,
      action,
      timestamp: new Date().getTime()
    })

    // 最多保留100条记录
    if (shortcutHistory.length > 100) {
      shortcutHistory.shift()
    }
  }

  // 显示快捷键提示
  const showShortcutHint = (label, combo) => {
    const keys = combo.split('+').map(k => {
      const keyMap = {
        'ctrl': 'Ctrl',
        'shift': 'Shift',
        'alt': 'Alt',
        'meta': 'Cmd'
      }
      return keyMap[k.toLowerCase()] || k.toUpperCase()
    }).join(' + ')

    ElMessage({
      message: `${label} (${keys})`,
      type: 'info',
      duration: 1500,
      showClose: false,
      grouping: true
    })
  }

  // 注册快捷键
  const register = (combo, handler, config = {}) => {
    const shortcutConfig = {
      handler,
      ...config
    }
    
    if (scope === 'global') {
      globalShortcuts.set(combo, shortcutConfig)
    } else {
      activeShortcuts.value.set(combo, shortcutConfig)
    }
  }

  // 注销快捷键
  const unregister = (combo) => {
    if (scope === 'global') {
      globalShortcuts.delete(combo)
    } else {
      activeShortcuts.value.delete(combo)
    }
  }

  // 批量注册
  const registerBatch = (shortcuts) => {
    Object.entries(shortcuts).forEach(([combo, config]) => {
      register(combo, config.handler || config, config)
    })
  }

  // 启用/禁用快捷键
  const enable = () => {
    isEnabled.value = true
  }

  const disable = () => {
    isEnabled.value = false
  }

  // 获取所有快捷键
  const getAllShortcuts = () => {
    const all = new Map()
    
    // 全局快捷键
    globalShortcuts.forEach((config, combo) => {
      all.set(combo, { ...config, scope: 'global' })
    })
    
    // 局部快捷键
    activeShortcuts.value.forEach((config, combo) => {
      all.set(combo, { ...config, scope: 'local' })
    })
    
    return all
  }

  // 获取快捷键列表（用于显示）
  const getShortcutList = computed(() => {
    const list = []
    
    Object.entries(mergedShortcuts).forEach(([combo, config]) => {
      if (typeof config === 'object') {
        list.push({
          combo,
          label: config.label || combo,
          icon: config.icon,
          action: config.action
        })
      }
    })
    
    return list
  })

  // 检查快捷键冲突
  const checkConflicts = () => {
    const conflicts = []
    const comboMap = new Map()
    
    Object.keys(mergedShortcuts).forEach(combo => {
      if (comboMap.has(combo)) {
        conflicts.push({
          combo,
          first: comboMap.get(combo),
          second: mergedShortcuts[combo]
        })
      } else {
        comboMap.set(combo, mergedShortcuts[combo])
      }
    })
    
    return conflicts
  }

  // 获取使用统计
  const getUsageStats = () => {
    const stats = {}
    
    shortcutHistory.forEach(record => {
      if (!stats[record.shortcut]) {
        stats[record.shortcut] = {
          count: 0,
          lastUsed: 0
        }
      }
      stats[record.shortcut].count++
      stats[record.shortcut].lastUsed = Math.max(
        stats[record.shortcut].lastUsed,
        record.timestamp
      )
    })
    
    return stats
  }

  // 生命周期
  onMounted(() => {
    if (scope === 'global') {
      window.addEventListener('keydown', handleKeyDown, true)
      window.addEventListener('keyup', handleKeyUp, true)
    } else {
      document.addEventListener('keydown', handleKeyDown)
      document.addEventListener('keyup', handleKeyUp)
    }
  })

  onUnmounted(() => {
    if (scope === 'global') {
      window.removeEventListener('keydown', handleKeyDown, true)
      window.removeEventListener('keyup', handleKeyUp, true)
    } else {
      document.removeEventListener('keydown', handleKeyDown)
      document.removeEventListener('keyup', handleKeyUp)
    }
  })

  return {
    isEnabled,
    pressedKeys,
    lastKeyCombo,
    shortcutList: getShortcutList,
    register,
    unregister,
    registerBatch,
    enable,
    disable,
    getAllShortcuts,
    checkConflicts,
    getUsageStats
  }
}

/**
 * 快捷键提示面板
 */
export function useShortcutHints() {
  const visible = ref(false)
  const shortcuts = ref([])

  const show = (shortcutList) => {
    shortcuts.value = shortcutList
    visible.value = true
  }

  const hide = () => {
    visible.value = false
  }

  const toggle = () => {
    visible.value = !visible.value
  }

  return {
    visible,
    shortcuts,
    show,
    hide,
    toggle
  }
}

/**
 * 快捷键录制器
 */
export function useShortcutRecorder() {
  const isRecording = ref(false)
  const recordedCombo = ref('')

  const startRecording = () => {
    isRecording.value = true
    recordedCombo.value = ''
  }

  const stopRecording = () => {
    isRecording.value = false
    return recordedCombo.value
  }

  const handleRecordKey = (event) => {
    if (!isRecording.value) return

    const parts = []
    if (event.ctrlKey) parts.push('Ctrl')
    if (event.shiftKey) parts.push('Shift')
    if (event.altKey) parts.push('Alt')
    if (event.metaKey) parts.push('Cmd')
    
    const key = event.key
    if (!['Control', 'Shift', 'Alt', 'Meta'].includes(key)) {
      parts.push(key.toUpperCase())
    }
    
    recordedCombo.value = parts.join(' + ')
  }

  onMounted(() => {
    document.addEventListener('keydown', handleRecordKey)
  })

  onUnmounted(() => {
    document.removeEventListener('keydown', handleRecordKey)
  })

  return {
    isRecording,
    recordedCombo,
    startRecording,
    stopRecording
  }
}

